package com.netty.demo.text.line;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class TelnetClient {

    private static final int PORT = 5001;
    private static final String HOST = "127.0.0.1";

    public static void main(String[] args)throws Exception{
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bs = new Bootstrap();
            bs.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new TelnetclientInitializer());
            Channel ch = bs.connect(HOST, PORT).sync().channel();

            ChannelFuture lastWriteFuture = null;
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            for (;;){
                String line = in.readLine();
                if (line == null){
                    break;
                }
                lastWriteFuture = ch.writeAndFlush(line + "\r\n");
                if ("bye".equals(line.toLowerCase())) {
                    ch.closeFuture().sync();
                    System.out.println("=================退出对话===================");
                }

                if(lastWriteFuture != null){
                    lastWriteFuture.sync();
                }
            }
        }finally {
            group.shutdownGracefully();
        }
    }

}
